#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include "methods.h"
#include <QDateTime>
#include <QFileDialog>
#include <QMessageBox>
#include <qdir.h>
#include <qfiledialog.h>
#include <qobject.h>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow) {
  ui->setupUi(this);
  int a = 0;
}

MainWindow::~MainWindow() { delete ui; }
void MainWindow::on_btn_jia_clicked() {

  double a = ui->txt_a->text().toDouble();
  double b = ui->txt_b->text().toDouble();

  double result = my_add(a, b);

  ui->txt_result->setText(QString::number(result, 'f').simplified());
}

void MainWindow::on_btn_jian_clicked() {
  double result =
      my_sub(ui->txt_a->text().toDouble(), ui->txt_b->text().toDouble());

  ui->txt_result->setText(QString::number(result, 'f').simplified());
}

void MainWindow::on_btn_cheng_clicked() {
  double result =
      my_mult(ui->txt_a->text().toDouble(), ui->txt_b->text().toDouble());

  ui->txt_result->setText(QString::number(result, 'f').simplified());
}

void MainWindow::on_btn_chu_clicked() {
  double result =
      my_div(ui->txt_a->text().toDouble(), ui->txt_b->text().toDouble());

  ui->txt_result->setText(QString::number(result, 'f').simplified());
}

void MainWindow::on_btn_swap_clicked() {
  double a = ui->txt_a->text().toDouble();
  double b = ui->txt_b->text().toDouble();

  my_swap(&a, &b);

  ui->txt_a->setText(QString::number(a, 'f').simplified());
  ui->txt_b->setText(QString::number(b, 'f').simplified());
}

void MainWindow::on_btn_save_clicked() {

  QDateTime dateTime = QDateTime::currentDateTime(); // 获取系统当前的时间

  QString str = dateTime.toString("yyyy-MM-dd hh:mm:ss"); // 格式化时间

  QString textFile = QFileDialog::getSaveFileName(
      this, tr("Save File"), "/home/mylikes/Datas/" + str + ".txt",
      tr("Text files (*.txt)"));

  QFile file(textFile);

  // 检测文件是否打开
  if (!file.open(QFile::WriteOnly | QFile::Text)) {
    QMessageBox::information(this, tr("Error Message"),
                             tr("Please Select a Text File!"));
    return;
  }
  QTextStream out(&file); // 分行写入文件
  out << ui->txt_save->toPlainText();
  QMessageBox::information(this, tr("Finish"),
                           tr("Successfully save the file!"));
  file.close();
}